package de.tudarmstadt.fgbs.cafe.data;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import de.tudarmstadt.fgbs.cafe.structure.Fahrplan;
import de.tudarmstadt.fgbs.cafe.structure.Zuglauf;

public class SimpleSystemDataManager implements SystemDataManagerInterface {

    private List<Fahrplan> fahrplaene;

    public SimpleSystemDataManager() {
	fahrplaene = new ArrayList<Fahrplan>();
    }

    @Override
    public int createFPL(String name) {
	Fahrplan newFPL = new Fahrplan();
	newFPL.setName(name);
	fahrplaene.add(newFPL);
	return fahrplaene.lastIndexOf(newFPL);
    }

    @Override
    public boolean addZL(int fplID, Zuglauf zl) {
	return fahrplaene.get(fplID).addZuglauf(zl);
    }

    @Override
    public Map<Integer, Fahrplan> retrieveAllFPL() {
	Map<Integer, Fahrplan> result = new HashMap<Integer, Fahrplan>();
	for (int i = 0; i < fahrplaene.size(); i++) {
	    result.put(i, fahrplaene.get(i));
	}
	return result;
    }

    @Override
    public Fahrplan retrieveFPL(int id) {
	return fahrplaene.get(id);
    }

    @Override
    public Zuglauf retrieveZL(int fplID, String zlNr) {
	return fahrplaene.get(fplID).getZuglauf(zlNr);
    }

    @Override
    public Fahrplan retrieveFPL(String name) {
	for (Iterator<Fahrplan> it = fahrplaene.iterator(); it.hasNext();) {
	    Fahrplan current = it.next();
	    if (current.getName().equals(name)) {
		return current;
	    }
	}
	return null;
    }

    @Override
    public void addFPL(Fahrplan fpl) {
	fahrplaene.add(fpl);
    }

    @Override
    public int getFPLID(Fahrplan fpl) {
	return fahrplaene.lastIndexOf(fpl);
    }

    @Override
    public void removeFPL(String name) {
	for (Iterator<Fahrplan> it = fahrplaene.iterator(); it.hasNext();) {
	    Fahrplan current = it.next();
	    if (current.getName().equals(name)) {
		it.remove();
		return;
	    }
	}
    }

    @Override
    public void removeFPL(int id) {
	fahrplaene.remove(id);
    }

    @Override
    public Fahrplan mergeFPLs(String[] names) {
	Fahrplan merged = new Fahrplan();
	merged.setRevision(0);

	Date date = new Date();
	SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
	merged.setName(dt.format(date) + "-merged");

	for (int i = 0; i < names.length; i++) {
	    Fahrplan current = retrieveFPL(names[i]);
	    for (Iterator<Zuglauf> it = current.getZuglaeufe().iterator(); it
		    .hasNext();) {
		Zuglauf curZL = it.next();
		merged.addZuglauf(curZL);
	    }
	    merged.linkZuglaeufe();
	}

	addFPL(merged);
	return merged;
    }

}
